package dwetl.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class ConfigUtil {

    public static JSONObject loadJsonFromClassPath(String jsonPath) throws IOException {

        ClassPathResource resource = new ClassPathResource(jsonPath);

        JSONObject instance= JSON.parseObject(resource.getInputStream(), StandardCharsets.UTF_8, JSONObject.class,
                // 自动关闭流
                Feature.AutoCloseSource,
                // 允许注释
                Feature.AllowComment,
                // 允许单引号
                Feature.AllowSingleQuotes,
                // 使用 Big decimal
                Feature.UseBigDecimal);
        return instance;
    }

    private static DateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
    private static DateFormat datetimeFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static long ONE_DAY_MS=1000*3600*24;
    public static long ONE_HOUR_MS=1000*3600;

    public static Date parseDate(String d){
        try {
            if("0000-00-00".equals(d)){
                return null;
            }
            Date md = datetimeFormat.parse(d);
            return md;
        }catch(Exception e){
            return null;
        }
    }

    public static Date parseDateTime(String dt){
        try {
            if("0000-00-00 00:00:00".equals(dt)){
                return null;
            }
            Date md = datetimeFormat.parse(dt);
            return md;
        }catch(Exception e){
            return null;
        }
    }

    public static String formatDateTime(Date d){//datetimeFormat.setTimeZone(TimeZone.getDefault());
        return datetimeFormat.format(d);
    }

    public static String formatDate(Date d){//dateFormat.setTimeZone(TimeZone.getDefault());
        return dateFormat.format(d);
    }
}
